import request from 'request';
import express from 'express';

const app = express();
app.use(express.static('public'));

const proxyTable = {
  '/api': {
    target: 'http://localhost/api',
  },
};

app.use(function (req, res, next) {
  const url = req.url;
  console.log('received request:', url);
  if (req.method == 'OPTIONS') {
    res.status(200).send('OK');
    return;
  }
  next();
});

app.use('/', function (req, res) {
  const url = req.url;
  const proxy = Object.keys(proxyTable);
  let not_found = true;
  for (let index = 0; index < proxy.length; index++) {
    const k = proxy[index];
    const i = url.indexOf(k);
    if (i >= 0) {
      not_found = false;
      const element = proxyTable[k];
      const newUrl = element.target + url.slice(i + k.length);
      req
        .pipe(
          request({ url: newUrl, timeout: 60000 }, (err) => {
            if (err) {
              console.log('error_url: ', err.code, url);
              res.status(500).send('');
            }
          })
        )
        .pipe(res);
      break;
    }
  }
  if (not_found) {
    res.status(404).send('Not found');
  }
});
const PORT = 9527;
app.listen(PORT, () => {
  console.log('HTTP Server is running on: http://localhost:%s', PORT);
});
